<?php

namespace Apps\AppApi\Method\Note;

use Apps\AppApi\Method\BaseMethod;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\AccountBook;
use Phalcon\Mvc\Model;


/**
 * 修改欠款记录（缴欠款）
 * @author      545
 * @date        2016年3月4日
 * @version     1.1.2
 * @copyright   Copyright 2015 meelier.com
 */
class ModifyArrears extends BaseMethod
{
    
    private $success = 0;
    private $id = 0;
    private $message = '';

    public function run()
    {
        //验证是否登录
        if(false == $this->verifyUserAuth()){
            return false;
        }
        //欠款记录id
        $ab_id = $this->getDataItem('ab_id',0);
        $nownum = $this->getDataItem('nownum',0);
        $addtime = $this->getDataItem('addtime',date("Y-m-d H:i:s", time()));
    	$addtime = date("Y-m-d H:i:s",strtotime($addtime));
    	
        if ($ab_id ==0){
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR,"id不能为空");
        }
        if ($nownum ==0){
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR,"本次金额不能为空");
        }
        $userid = $this->getUserAuth()->userId;
        
        //查询欠款记录
        $data = AccountBook::findFirst("ab_id = {$ab_id}  AND user_id = {$userid}");
    	//如果欠款存在
    	if ($data){
    	    $num = $data->ab_arrears-$nownum>0?$data->ab_arrears-$nownum:0;
    	    
    	    $data->update(['ab_arrears'=>$num]);
    	    
    	    //生成一条记录
    	    $temp['ab_cashnum'] = $nownum;
        	$temp['ab_innoroutid'] = $data->ab_innoroutid;
        	$temp['child_inoroutid'] = $data->child_inoroutid;
        	$temp['ab_type'] = $data->ab_type;
        	$temp['ab_memberid'] = $data->ab_memberid;
        	$temp['ab_arrears'] = 0;
        	$temp['remark'] = '';
        	$temp['createtime'] = date("Y-m-d H:i:s", time());
        	$temp['user_id'] = $userid;
        	$temp['addtime'] = $addtime;
        	
        	$a = new AccountBook();
        	if ($a->save($temp)){
        	    $this->success = 1;
        	    $this->message = "成功";
        	}
        	else {
        	    $this->success = 0;
        	    $this->message ="失败";
        	}
    	}
    	else {
    	    $this->success = 0;
    	    $this->message ="失败";
    	}
    	
        $this->setResult(['success'=>$this->success,'message'=>$this->message]);
        
    }

}